<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Paginator;
use think\paginator\driver\Bootstrap;
/**
 * 标签库
 *
 * @wangchao
 */
class Mark extends Backend
{
    
    /**
     * Mark模型对象
     * @var \app\admin\model\Mark
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Mark;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
        查看
     **/

    public function index(){


        $type = config('config.mark-type');
        $this->view->assign("type",$type);

        $search=input("get.type");
       /// dump($search);
        if($search=="0" || $search==''){
            $where['mark_type']=array("in","0,1,2,3,4,5,6,7,8");
            $where_search=0;
        }else{
            $where['mark_type']=$search;
            $where_search=$search;
        }
       // dump($where);

        $list =db("mark")->where($where)->order("id asc")->select();
        //dump($list);
        $all_idents=$this->_findChildren($list,0);

        $curPage = input('get.page') ? input('get.page') : 1;//接收前段分页传值
        $listRow = 15;//每页2行记录
        $showdata = array_slice($all_idents, ($curPage - 1)*$listRow, $listRow,true);// 数组中根据条件取出一段值，并返回

        $p = Bootstrap::make($showdata, $listRow, $curPage, count($all_idents), false, [
            'var_page' => 'page',
            'path'     => url("/admin/mark/index"),//这里根据需要修改url
            'query'    => [],
            'fragment' => '',
        ]);
        $p->appends($_GET);
        $this->assign('list', $p);
        $this->assign('listpage', $p->render());
        $this->assign("search",$where_search);
        return $this->view->fetch();
    }


    function _findChildren($list, $p_id){    //数据层级化，
        $r = array();
        foreach($list as $id=>$item){
            if($item['fid'] == $p_id) {
                $length = count($r);
                $r[$length] = $item;
                if($t = $this->_findChildren($list, $item['id']) ){
                    $r[$length]['children'] = $t;
                }else{
                    $r[$length]['children'] = "";
                }

            }
        }
        return $r;
    }

    public function resort($data,$fid=0,$level=1){
        static $ret=array();
        foreach ($data as $k=>$v) {
            if($v['fid']==$fid){
                $v['m_level']=$level;
                $ret[]=$v;
                $this->resort($data,$v['id'],$level+1);
            }
        }
        return $ret;
    }

    /**
        添加
     **/
    public function mark_add(){
        $type = config('config.mark-type');
        $this->view->assign("type",$type);
        $fid=input("get.fid");
        if($fid){
            $res=$this->model->find($fid)->toArray();
            $this->assign("res",$res);
            $m_level=$res['m_level']+1;
        }else{
            $m_level=1;
        }
        $this->assign("fid",$fid);
        if(Request()->isPost()){
            $data = input("post.");
            $mark_info=$data['mark_info'];
            $result=db("mark")->where("mark_info",$mark_info)->find();
            if($result['mark_info']){
                $this->error("该标签已存在！");
            }
            if($fid!=0){
                $data['mark_type']=$res['mark_type'];
            }
            $data['m_level']=$m_level;
            $row = $this->model->insert($data);
            if($row){
                $this->success("添加标签成功！","/admin/mark/index");
            }else{
                $this->error("添加失败！");
            }
        }
        return $this->view->fetch();
    }

    /**
        修改
     **/
    public function mark_edit(){
        $type = config('config.mark-type');
        $this->view->assign("type",$type);
        $id = input("get.id");
        $mark=db("mark");
        if($id){
            $row =$mark->find($id);;
            $markList= $mark->where("status",0)->select();
            $markList=$this->resort($markList);
            $this->view->assign("row", $row);
            $this->view->assign("markList", $markList);
        }
        if (Request()->isPost()){
            $data = input("post.");
            //dump($data);


            $this->set_father_mark($data['id'],$data['fid']);
            $update['id']=$data['id'];
            $update['fid']=$data['fid'];
            $update['mark_info']=$data['mark_info'];
            $update['ishot']=$data['ishot'];
            $update['status']=$data['status'];
            $update['linkto']=$data['linkto'];
            $res = $this->model->update($update);
            if($res){
                $this->success("修改成功！","/admin/mark/index");
            }else{
                $this->error("修改失败！");
            }
        }
        return $this->view->fetch();
    }

    //判断是否层级溢出

    function set_father_mark($id,$fid){
        $mark=db("mark");
        //获取父节点层级
        $level=$mark->find($fid);

        if($fid==0){
            $level['m_level']=0;
        }
       /* echo "父级";
        dump($level);*/
        //获取当前标签及所有子节点的最大层级

      //  echo "当前";
        $res=$mark->find($id);
      ///  dump($res);
        $list=$mark->where("status",0)->select();
        $data=$this->resort($list,$res['id'],$res['m_level']+1);
      /*  echo "当前的所有子节点";
        dump($data);*/
        ///die;
        $valArr = array();
        foreach ($data as $key=>$value) {
            $valArr[$key] = $value['m_level'];
        }

        asort($valArr);

        $valArr= array_unique($valArr);
       // dump($valArr);
        //die;
        $count=count($valArr);
        $flag=$count+$level['m_level']+1;
       // dump($flag);
        //die;
        if($flag>6){
            $this->error("层级不合法,请重新选择父级标签！");
        }
       /* if($level['m_level']<=$res['m_level']){
            $tamp=$res['m_level']-$level['m_level']+1;
        }else{
            $tamp=$res['m_level']-$level['m_level']+1;
        }*/
        $tamp=intval($res['m_level'])-intval($level['m_level']+1);
        ///dump($tamp);
        //dump(intval($tamp));
       // die;
        foreach($data as $key=>$value){
            $update['m_level']=intval($value['m_level'])-intval($tamp);
            if($fid!=0){
                $update['mark_type']=$level['mark_type'];
            }

            $mark->where("id",$value['id'])->update($update);
        }
        $update1['m_level']=intval($res['m_level'])-intval($tamp);
        if($fid!=0){
            $update1['mark_type']=$level['mark_type'];
        }
        $mark->where("id",$id)->update($update1);
    }














    /**
    删除
     **/
    public function mark_del(){
        $mark=db("mark");
        $id = input("post.id");
       // dump($id);die;
        $res=$mark->find($id);
        $list=$mark->where("status",0)->select();
        $data=$this->resort($list,$res['id'],$res['m_level']+1);

        //dump($data);die;
        $product_mark=db("product_mark");
        foreach($data as $k=>$v){

            $mark_data=$product_mark->where("mark_id",$v['id'])->select();
            foreach($mark_data as $k1=>$v1){
                $product_mark_res=$product_mark->delete($v1['id']);
                if(!$product_mark_res){
                    ajaxMsg("子节点产品标签删除失败",0);
                }
            }
            $row=$mark->delete($v['id']);
            if(!$row){
                ajaxMsg("子节点删除失败",0);
            }
        }


        $result_mark_data=$product_mark->where("mark_id",$id)->select();
        foreach($result_mark_data as $k2=>$v2){
            $product_mark_result=$product_mark->delete($v2['id']);
            if(!$product_mark_result){
                ajaxMsg("产品标签删除失败",0);
            }
        }
        $result=$mark->delete($id);
        if($result){
            ajaxMsg("标签删除成功",1);
        }else{
            ajaxMsg("标签删除失败",0);
        }

    }


    //子节点排序

    public function mark_sort(){
        $fid=input("get.fid");
        $list=db("mark")->where(['fid'=>$fid,"status"=>0])->select();
        $this->assign("list",$list);
        return  $this->view->fetch();
    }

    public function mark_sort_sub(){
        $data=$_REQUEST['arr'];
        $count=0;
        foreach($data as $k=>$v){
            $sort=explode("-",$v);
           $res= db("mark")->where("id",$sort[0])->update(["m_order"=>$sort[1]]);
            if($res){
                $count++;
            }
        }
        if($count>0){
              ajaxMsg("排序成功",1);
        }else{
            ajaxMsg("排序失败",0);
        }
    }
















}
